import { useState, useEffect } from 'react';
import { 
  Table, Button, Space, Modal, Form, Input, Select,message, Row, Col 
} from 'antd';
import axios from 'axios';

const { Option } = Select;


const UserList = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm();
    const [editingId, setEditingId] = useState(null);
    const [searchForm] = Form.useForm(); // 新增搜索表单

    // 搜索参数
  const [searchParams, setSearchParams] = useState({
    username: '',
    email: '',
    role: ''
  });

    // 获取用户数据（改造后）
    const fetchUsers = async (params = {}) => {
      setLoading(true);
      try {
        const res = await axios.get('/api/users', {
          params: {
            ...params,
          }
        });
        setData(res.data);
      } catch (error) {
        console.error('数据加载失败:', error);
      }
      setLoading(false);
    };

    // 搜索提交
  const handleSearch = (values) => {
    setSearchParams(values);
    fetchUsers(values);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    fetchUsers();
  };

  // 初始化加载
  useEffect(() => {
    fetchUsers();
  }, []);

    // 表格列配置
    const columns = [
        { title: '姓名', dataIndex: 'username' },
        { title: '邮箱', dataIndex: 'email' },
        { title: '角色', dataIndex: 'role' },
        {
            title: '操作',
            render: (_, record) => (
                <Space>
                    <Button onClick={() => handleEdit(record)}>编辑</Button>
                    <Button danger onClick={() => handleDelete(record.id)}>删除</Button>
                </Space>
            )
        }
    ];

    // 编辑操作
    const handleEdit = (record) => {
        form.setFieldsValue(record);
        setEditingId(record.id);
        setIsModalOpen(true);
    };

    // 删除操作
    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/users/${id}`);
            message.success('删除成功');
            fetchUsers();
        } catch (error) {
            message.error('删除失败');
        }
    };

    // 表单提交
    const handleSubmit = async (values) => {
        try {
            if (editingId) {
                await axios.put(`/api/users/${editingId}`, values);
                message.success('更新成功');
            } else {
                await axios.post('/api/users', values);
                message.success('创建成功');
            }
            setIsModalOpen(false);
            form.resetFields();
            fetchUsers();
        } catch (error) {
            message.error('操作失败');
        }
    };

    return (
        <div>
          {/* 新增搜索表单 */}
          <Form form={searchForm} onFinish={handleSearch}>
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item name="name" label="姓名">
                  <Input placeholder="请输入姓名" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="email" label="邮箱">
                  <Input placeholder="请输入邮箱" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="role" label="角色">
                  <Select placeholder="请选择角色">
                    <Option value="运维">运维</Option>
                    <Option value="测试">测试</Option>
                    <Option value="开发">开发</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                  <Button onClick={handleReset}>
                    重置
                  </Button>
                </Space>
              </Col>
            </Row>
          </Form>

            <div style={{ marginBottom: 16, textAlign: 'right' }}>
                <Button 
                    type="primary"
                    onClick={() => {
                        setEditingId(null);
                        setIsModalOpen(true);
                        form.resetFields();
                    }}
                >
                    新建用户
                </Button>
            </div>

            <Table
                columns={columns}
                dataSource={data}
                loading={loading}
                rowKey="id"
                bordered
                pagination={{ pageSize: 8 }}
            />

            {/* 编辑/新建模态框 */}
            <Modal
                title={editingId ? '编辑用户' : '新建用户'}
                open={isModalOpen}
                onCancel={() => setIsModalOpen(false)}
                footer={null}
            >
                <Form form={form} onFinish={handleSubmit}>
                    <Form.Item label="姓名" name="username" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="邮箱" name="email" rules={[{ type: 'email' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="角色" name="role">
                        <Input />
                    </Form.Item>
                    <Button type="primary" htmlType="submit">提交</Button>
                </Form>
            </Modal>
        </div>
    );
};

export default UserList;